package com.lxz.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lxz.usercenter.common.ErrorCode;
import com.lxz.usercenter.constant.UserConstant;
import com.lxz.usercenter.exception.BusinessException;
import com.lxz.usercenter.model.domain.User;
import com.lxz.usercenter.service.UserService;
import com.lxz.usercenter.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 用户密码加盐
     */
    public static final String SALT = "lxz";

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {


        //校验账户密码以及校验密码是否位空
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword)) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //检验账户长度
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账户过短");
        }

        //检验密码及校验密码长度
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }

        //检验密码是否一致
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"校验密码不一致");
        }

        //账号是否有特殊字符
        final String REGEX = "^[a-zA-Z0-9]+$";
        if (!Pattern.matches(REGEX, userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }

        //检验是否账户重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账户已存在");
        }

        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + SALT).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);


        //保存进数据库
        boolean save = this.save(user);
        if (!save) {
            return -1;
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //校验账户密码以及校验密码是否位空
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //检验账户长度
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账户过短");
        }


        //账号是否有特殊字符
        final String REGEX = "^[a-zA-Z0-9]+$";
        if (!Pattern.matches(REGEX, userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }

        //检验密码长度
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }

        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + SALT).getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.getOne(queryWrapper);

        if (user == null) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }

        //用户脱敏
        User newUser = getSafetyUser(user);


        //将登录信息存入session
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, newUser);

        //返回脱敏后的用户
        return newUser;
    }


    /**
     * 获取脱敏用户
     *
     * @param user
     * @return
     */
    @Override
    public User getSafetyUser(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //用户脱敏
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setUsername(user.getUsername());
        newUser.setUserAccount(user.getUserAccount());
        newUser.setAvatarUrl(user.getAvatarUrl());
        newUser.setGender(user.getGender());
        newUser.setPhone(user.getPhone());
        newUser.setEmail(user.getEmail());
        newUser.setUserRole(user.getUserRole());
        newUser.setTags(user.getTags());
        newUser.setProfile(user.getProfile());
        newUser.setUserStatus(user.getUserStatus());
        newUser.setCreateTime(user.getCreateTime());
        return newUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        //将用户信息从session中移除
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 根据标签搜索用户
     *
     * @param tagNameList
     * @return
     */
    @Override
    public List<User> searchUserByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        for (String tagName: tagNameList) {
            queryWrapper=queryWrapper.like("tags",tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
      return  userList.stream().map(this::getSafetyUser).collect(Collectors.toList());

    }


    /**
     * 判断用户是否为管理员
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        //权限验证
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user= (User) userObj;
        if(user==null||user.getUserRole()!=UserConstant.ADMIN_ROLE){
            return false;
        }
        return true;
    }

    /**
     * 判断用户是否为管理员
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        if(loginUser==null||loginUser.getUserRole()!=UserConstant.ADMIN_ROLE){
            return false;
        }
        return true;
    }


    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @Override
    public User getCurrentUser(HttpServletRequest request) {
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user= (User) userObj;
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        return user;
    }


    /**
     * 更新用户信息
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if(userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断是否为管理员
        //不是管理员，不能修改其他用户信息
        if(!isAdmin(loginUser)&& !loginUser.getId().equals(userId)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        User oldUser = this.getById(userId);
        if(oldUser==null){
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

}




